package org.deng.vertx.web.controller;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.deng.vertx.web.entity.User;

import io.vertx.core.Vertx;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.Json;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 邓力宾
 * @date 2021/8/25 17:18
 * @desc
 */
@Slf4j
public class UserController implements RouterController {
    private AtomicLong id = new AtomicLong(1);
    private Vertx vertx;
    public UserController(Vertx vertx){
        this.vertx = vertx;
    }
    /**
     * 配置路由
     * @param router
     */
    @Override
    public void configRouter(Router router) {
        log.info("配置UserController");
        router.route("/user/list").method(HttpMethod.GET).handler(this::userList);
        router.route("/user/add").method(HttpMethod.GET).handler(this::add);
    
    }



    /**
     * 获取用户列表
     * @param ctx
     */
    private void userList(RoutingContext ctx){
        log.info("用户列表");
        List<User> users = new LinkedList<>();
        users.add(new User(1L, "张三", 23, LocalDateTime.now()));
        users.add(new User(2L, "李四", 24, LocalDateTime.now()));
        ctx.json(users);
    }

    /**
     * 添加用户
     * @param ctx
     */
    private void add(RoutingContext ctx){

        log.info("添加用户");
        User user = new User(id.incrementAndGet(), "李四-"+id.get(), 24, null);
        EventBus bus = vertx.eventBus();
        //发送消息
        bus.request("userDao::insert", Json.encode(user), reply ->{
            HttpServerResponse response =  ctx.request().response();
            response.headers().set("Content-Type", "application/json;charset:utf-8");
            response.end((String) reply.result().body());
        });        
    }
}
